#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>

#define wait_key getchar
#if defined(__unix__) || defined(__unix)
#include <sys/wait.h>
#endif
#include <string.h>

#ifdef __MINGW32__
int _CRT_glob = 0;
#endif

bool hasSpaces( const char* str ) {
  char last = 0;
  while( str && *str ) {
    if( ( *str == ' ' || *str == '\t' ) && last != '\\' ) {
      return true;
    }
    last = *str++;
  }
  return false;
}

int execute_command( char *cmdline ) {
  int ret = system( cmdline );
  if( WIFEXITED( ret ) ) {
    return WEXITSTATUS( ret );
  } else {
    return -1;
  }
}

int main( int argc, char** argv ) {
  if( argc < 2 ) {
    printf( "Usage: cb_console_runner <filename> <args ...>\n" );
    return 1;
  }
  size_t fullsize = 0;
  for( int i = 1; i < argc; ++i ) {
    fullsize += strlen( argv[i] );
  }
  fullsize += argc + 32;
  char* cmdline = new char[fullsize];
  memset( cmdline, 0, fullsize );
  bool sp = hasSpaces( argv[1] );
  if( sp ) {
    strcat( cmdline, "\"" );
  }
  strcat( cmdline, argv[1] );
  if( sp ) {
    strcat( cmdline, "\"" );
  }
  strcat( cmdline, " " );
  for( int i = 2; i < argc; ++i ) {
    sp = hasSpaces( argv[i] );
    if( sp ) {
      strcat( cmdline, "\"" );
    }
    strcat( cmdline, argv[i] );
    if( sp ) {
      strcat( cmdline, "\"" );
    }
    strcat( cmdline, " " );
  }
  timeval tv;
  gettimeofday( &tv, NULL );
  double cl = tv.tv_sec + ( double )tv.tv_usec / 1000000;
  int ret = execute_command( cmdline );
  gettimeofday( &tv, NULL );
  cl = ( tv.tv_sec + ( double )tv.tv_usec / 1000000 ) - cl;
  printf( "\nProcess returned %d (0x%X)   execution time : %0.3f s", ret, ret, cl );
  printf
  (
    "\nPress "
    "ENTER"
    " to continue.\n"
  );
  wait_key();
  delete[] cmdline;
  return ret;
}
